package server.thread;

import server.catalina.Service;
import server.catalina.mapper.Context;
import server.catalina.mapper.Host;
import server.catalina.mapper.Wrapper;
import server.common.Request;
import server.common.Response;
import server.servlet.HttpServlet;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

/**
 *
 */
public class RequestProcessorNew extends Thread{
    private  Socket socket;
    private Service service;

    public RequestProcessorNew(Socket socket, Service service) {
        this.socket = socket;
        this.service = service;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();
            //封装Resuest对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            String url = request.getUrl();
            String[] split = url.split("/");
            Map<String, Host> hostMap = service.getEngine().getMapper().getHostMap();
            Host host = hostMap.get(request.getHost());
            Map<String, Context> contextMap = host.getContextMap();
            Context context = contextMap.get(split[1]);
            Map<String, Wrapper> wrapperMap = context.getWrapperMap();
            if(wrapperMap.containsKey("/"+(split[2]))){
                Wrapper wrapper = wrapperMap.get("/"+split[2]);
                HttpServlet httpServlet = wrapper.getHttpServlet();
                httpServlet.service(request,response);
            }else{
                response.outputHtml(context.getContextAbsulotePath()+"\\"+split[2]);
            }

            socket.close();
        }catch (Exception e){

        }
    }
}
